package com.shopping.servelet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.shopping.entity.Goods;

@WebServlet("/Shopping")
public class Shopping extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String id=req.getParameter("id");  						//getParameter()获取参数,这里获取前端的id
		String name=req.getParameter("name");
		float price=Float.valueOf(req.getParameter("price"));
		int num=Integer.valueOf(req.getParameter("num")); 
		
		System.out.println(id+"\t"+name+"\t"+price+"\t"+num+"\t");
	
		HttpSession session=req.getSession(true);			//创建一个session，用来存储用户数据
		if(session.getAttribute("list1")==null){			//判断是否为空
			List<Goods> list=new ArrayList<>();
			Goods goods=new Goods();
			goods.setId(id);
			goods.setName(name);
			goods.setNum(num);
			goods.setPrice(price);
			list.add(goods);
			session.setAttribute("list1", list);
			System.out.println("创建session");
		}else{
			List<Goods> list=(List<Goods>) session.getAttribute("list1");	
			
//			for (Goods goods : list) {
//				System.out.println(goods);
//			}
			
			Goods goods=new Goods();										//实例化一个goods
			goods.setId(id);
			goods.setName(name);
			goods.setNum(num);
			goods.setPrice(price);
			list.add(goods);
			session.setAttribute("list1", list);
		}
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}
